package app

import (
	"context"
	"flag"
	"fmt"
	"net/http"
	"time"

	"code.bydev.io/cht/customer/kyc_admin_service/internal/app/serv"
	"code.bydev.io/cht/customer/kyc_admin_service/internal/config"
	"code.bydev.io/cht/customer/kyc_admin_service/internal/pkg/biz"
	nothingconfig "code.bydev.io/cht/customer/kyc_admin_service/internal/pkg/config"
	"code.bydev.io/cht/customer/kyc_admin_service/service/consumer"
	"code.bydev.io/cht/customer/kyc_admin_service/service/job"
	"code.bydev.io/cht/customer/kyc_admin_service/service/private"
	"code.bydev.io/frameworks/byone/core/conf"
	"code.bydev.io/frameworks/byone/core/logx"
	"code.bydev.io/frameworks/byone/core/service"
	"git.bybit.com/svc/go/pkg/bgrace"
	"git.bybit.com/svc/go/pkg/bgrace/bgracehttp"
	"go.elastic.co/apm"
	"gopkg.in/gographics/imagick.v3/imagick"
)

var configFile = flag.String("config", "kyc_admin.toml", "the config file")

func AppMain() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c, conf.UseEnv())
	c.MustSetUp()

	// 初始化供应商配置
	config.InitConfig(&c)

	// 加载nothing框架配置
	nothingconfig.Load()
	env, err := biz.InitEnvironment(context.Background(), c)
	logx.Must(err)

	// 初始化imagick对象
	imagick.Initialize()
	defer imagick.Terminate()

	//// 遗漏的http请求，等前端更换到grpc可以去掉
	go func(e *biz.Environment) {
		// HTTP download image
		imgImpl := serv.NewImgService(env)
		hmux := http.NewServeMux()
		hmux.HandleFunc("/kycadmin/image/download", imgImpl.DownloadHandler)
		httpAddr := fmt.Sprintf(":%d", nothingconfig.GetInt(nothingconfig.KeyHTTPPort))
		httpService := bgracehttp.New(env.Environment, hmux, httpAddr)
		bgrace.Serve(env.Environment, httpService)
		_ = env.Close()
		{
			ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
			defer cancel()
			apm.DefaultTracer.Flush(ctx.Done())
		}
	}(env)

	// byone框架初始化服务组
	serviceGroup := service.NewServiceGroup()
	serviceGroup.Add(job.JobService())
	serviceGroup.Add(consumer.ConsumerService())
	serviceGroup.Add(private.PrivateService(c))

	defer serviceGroup.Stop()
	fmt.Printf("Starting serviceGroup success....\n")
	serviceGroup.Start()
}
